#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
from flask import send_from_directory, Blueprint
import dbOperate

charts = Blueprint('charts', __name__)
db = dbOperate.dbOperate('10.37.128.49', 'zabbix', 'zabbix', 'zabbix')  ###爬虫数据库


###图表功能路由
@charts.route('/get_cpu_usage', methods=['GET'])
def get_cpu_usage():
    sql = 'select * from (SELECT hostname,itemname,ROUND(value,2) as value FROM history_last_item where  itemname = "CPU使用率" order by value desc limit 5) a order by value'  # sql语句
    see = db.exe_query(sql)
    hostname = []
    value = []
    jsonData = {}
    for data in see:
        hostname.append(data[0])
        value.append(data[2])
    jsonData['hostname'] = hostname
    jsonData['value'] = value
    j = json.dumps(jsonData, ensure_ascii=False)
    print('cpu--------' + str(len(j)))
    return j


@charts.route('/get_mem_usage', methods=['GET'])
def get_mem_usage():
    sql = 'select * from (SELECT hostname,itemname,ROUND(value,2) as value FROM history_last_item where  itemname = "内存使用率" order by value desc limit 5) a order by value'  # sql语句
    see = db.exe_query(sql)
    hostname = []
    value = []
    jsonData = {}
    for data in see:
        hostname.append(data[0])
        value.append(data[2])

    jsonData['hostname'] = hostname
    jsonData['value'] = value
    # print(len(jsonData))
    j = json.dumps(jsonData, ensure_ascii=False)
    print('mem--------' + str(len(j)))
    return j


@charts.route('/get_disk_usage', methods=['GET'])
def get_disk_usage():
    sql = 'select * from (SELECT hostname,itemname,ROUND(value,2) as value FROM history_last_item where  itemname = "硬盘使用率" order by value desc limit 5) a order by value'  # sql语句
    see = db.exe_query(sql)
    hostname = []
    value = []
    jsonData = {}
    for data in see:
        hostname.append(data[0])
        value.append(data[2])

    jsonData['hostname'] = hostname
    jsonData['value'] = value
    # print(len(jsonData))
    j = json.dumps(jsonData, ensure_ascii=False)
    print('disk--------' + str(len(j)))
    return j


@charts.route('/get_network_usage', methods=['GET'])
def get_network_usage():
    sql1 = 'select  ROUND(VALUE/1000000,2) as value  FROM history_uint_last	WHERE itemid IN ("32746","32698","35519","35520","32386","32338","35345","35346") order by field(itemid,"32746","32698","35519","35520","32386","32338","35345","35346");'
    see = db.exe_query(sql1)
    hostname = []
    value = []
    jsonData = {}
    i = 0
    for data in see:
        if i < 4:
            hostname.append(str(data[0]))
        else:
            value.append(str(data[0]))
        i += 1

    jsonData['hostname'] = hostname
    jsonData['value'] = value
    j = json.dumps(jsonData, ensure_ascii=False)
    print('jnetwork-------' + str(len(j)))
    return j


@charts.route('/download/')
def download():
    return send_from_directory("/root/rzitshow2/files", filename="temple.xls", as_attachment=True)
